<template>
  <el-tabs class="stock" v-model="activeName">
    <el-tab-pane label="已分配数据" name="first">
    </el-tab-pane>
    <div class="select-group">
      <div class="items">
        <span class="items-text">关键词</span>
        <el-select v-model="temp.keyword"
                   clearable
                   filterable
                   remote
                   :remote-method="key_remoteMethod"
                   :loading="keyLoading"
                   placeholder="请选择">
          <el-option
            v-for="(item,idx) in keyword"
            :key="idx"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </div>
      <div class="items">
        <span class="items-text">所属文件</span>
        <el-select v-model="temp.fileId" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in fileList"
            :key="item.fileId"
            :label="item.fileName"
            :value="item.fileId">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="select-group">
      <div class="items">
        <span class="items-text">呼叫结果</span>
        <el-select v-model="temp.call" @change="selectChange" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in callList"
            :key="item.callId"
            :label="item.callName"
            :value="item.callId">
          </el-option>
        </el-select>
      </div>
      <div class="items">
        <span class="items-text">转化结果</span>
        <el-select v-model="temp.vital" :disabled="temp.call !== 1" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in vitalList"
            :key="item.vitalId"
            :label="item.vitalName"
            :value="item.vitalId">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="select-group">
      <div class="items">
        <span class="items-text">系统标签</span>
        <el-select
          v-model="temp.sysLabel"
          clearable
          reserve-keyword
          filterable
          remote
          :remote-method="sys_remoteMethod"
          :loading="sysLoading"
          placeholder="请选择">
          <el-option
            v-for="(item,idx) in systemlabel"
            :key="idx"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </div>
      <div class="items">
        <span class="items-text">号码归属地</span>
        <el-cascader
          filterable
          clearable
          change-on-select
          :options="areaList"
          v-model="temp.areaOptions">
        </el-cascader>
      </div>
      <el-button v-waves
                 :disabled="listLoading"
                 size="medium"
                 type="success"
                 class="el-icon-search"
                 @click="getAllotList"
      >
        <span style="padding-left:5px;">查询</span>
      </el-button>
    </div>
    <h4>
      {{'批次名：' + folderName}}
      <el-button v-waves
                 @click="batchEvent(1)" class="eventBtn"
                 type="danger"
                 size="small"
                 icon="el-icon-delete">
        选中移除
      </el-button>
      <el-button v-waves
                 @click="batchEvent(2)" class="eventBtn"
                 type="danger"
                 size="small"
                 icon="el-icon-delete">
        批量移除
      </el-button>
      <el-button v-waves
                 @click="batchEvent(3)" class="eventBtn"
                 type="success"
                 size="small"
                 icon="el-icon-edit-outline">
        数据转发
      </el-button>
    </h4>
    <el-table @selection-change="handleSelectionChange"
              empty-text="暂无任何用户信息"
              :data="list"
              v-loading.body="listLoading"
              border
              fit
              style="width: 100%">
      <el-table-column
        align="center"
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column align="center" label="用户姓名">
        <template slot-scope="scope">
          <span>{{scope.row.customerName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="所属公司">
        <template slot-scope="scope">
          <span>{{ !!scope.row.companyName ? scope.row.companyName : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="行业">
        <template slot-scope="scope">
          <span>{{scope.row.industryName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="关键词">
        <template slot-scope="scope">
          <span>{{ !!scope.row.keyword ? scope.row.keyword : '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="系统标签">
        <template slot-scope="scope">
          <span>{{ !!scope.row.sysLabel ? scope.row.sysLabel : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="呼叫/转化">
        <template slot-scope="scope">
          <span>{{ !!scope.row.callVital ? callVitalText[scope.row.callVital - 1] : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="号码归属地">
        <template slot-scope="scope">
          <span>{{ scope.row.provinceName + ( scope.row.cityName === '' ? '' :  '/' + scope.row.cityName ) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="当前虚拟号">
        <template slot-scope="scope">
          <span>{{scope.row.virtualNumber}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="有效时间" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.lifeTime}}</span>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background
                     @size-change="handleSizeChange"
                     prev-text="上一页"
                     next-text="下一页"
                     @current-change="handleCurrentChange"
                     :current-page="listQuery.current"
                     :page-sizes="[10,20,30,50]"
                     :page-size="listQuery.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>

    <el-dialog width="400px"
               :title="eventStatus != 3 ? '移除' : '转发'"
               :visible.sync="infoFormVisible"
               @close="cancledialog('sendForm')"
    >
      <el-form :model="allot" :rules="rules" ref="sendForm">
        <!--这里必须套一个div 不然先点击批量后点击选中  弹框关闭时会报错-->
        <div>
          <el-form-item label="当前已选择 : "
                        v-show="eventStatus == 1"
                        :label-width="formLabelWidth">
            <span>{{ multipleSelection.length }} 条</span>
          </el-form-item>
        </div>
        <div>
          <el-form-item prop="batchCount"
                        v-if="eventStatus != 1 "
                        :label="eventStatus == 2 ? '批量移除条数' : '数据转发条数'"
                        :label-width="formLabelWidth">
            <el-input style="width: 200px;" v-model.number.sync="allot.batchCount" type="number" placeholder="请输入条数"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item prop="newFolder"
                        label="批次名称"
                        v-if="eventStatus == 3"
                        :label-width="formLabelWidth">
            <el-input style="width: 200px;" v-model.sync="allot.newFolder"  placeholder="请输入批次名称"></el-input>
          </el-form-item>
        </div>
        <el-form-item v-if="eventStatus == 3" label="所属公司" prop="allotSeleted" :label-width="formLabelWidth">
          <el-select v-model="allot.allotSeleted" clearable filterable placeholder="请选择">
            <el-option
              v-for="item in companyArr"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId">
            </el-option>
          </el-select>
        </el-form-item>
        <div>
          <el-form-item label="当前总条数 : "
                        :label-width="formLabelWidth">
            <span>{{ total }} 条</span>
          </el-form-item>
        </div>
        <div class="batchMark">
          {{ '注释:' + getMarkText(eventStatus)}}
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="getEventMethod(eventStatus)">{{ eventStatus != 3 ? '移除' : '转发' }}</el-button>
        <el-button @click="infoFormVisible = false" size="mini">取 消</el-button>
      </div>
    </el-dialog>
  </el-tabs>
</template>
<script>
  import { mapGetters } from 'vuex'
  import waves from '@/directive/waves' // 水波纹指令
  import {
    getCompany,
    getKeyword,
    getSyslabel,
    getAreaList
  } from '@/api/dataStock'
  import {getFileList, getAllotList, setAllot ,batchAllot ,transfert} from '@/api/allocation'

  export default {
    name: 'alloca-detial',
    directives: {
      waves
    },
    data() {
      const CheckBatchNum = (rule, value, callback) => {
        let tempValue = value * 1;
        let maxNum = this.totalTemp > this.maxBatchNum ? this.maxBatchNum : this.totalTemp;
        if (!value) {
          callback(new Error('请输入要分配的条数'));
        } else if (!Number.isInteger(tempValue) || tempValue < 1) {
          this.allot.batchCount = '';
          callback(new Error('输入必须是大于0的数字'));
        } else if(tempValue > maxNum){
          this.allot.batchCount = '';
          callback(new Error(maxNum >= this.maxBatchNum ? '单次处理不能大于'+ maxNum +'条数' : '输入值不能大于'+ maxNum +'条数'));
        }else{
          callback();
        }
      }
      return {
        sysLoading: false,
        keyLoading: false,
        activeName:'first',
        eventStatus:0,
        callVitalText:['未接听','已接听,未留','已接听,已留','未拨打'],
        callList:[
          {callId:1,callName:'已接听'},
          {callId:2,callName:'未接听'}
        ],
        vitalList:[
          {vitalId:1,vitalName:'已留'},
          {vitalId:2,vitalName:'未留'}
        ],
        temp:{}, //筛选列结果集,
        searchTemp:{}, //查询所用条件结果
        totalTemp:null,
        maxBatchNum:2000,
        areaList: [],
        fileList: [],
        companyArr:[],
        keyword: [],
        systemlabel: [],
        allot: {
          allotSeleted: '', //所要分配的公司id
          batchCount:null,
          newFolder:''
        },
        multipleSelection: [], //列选中的列id
        infoFormVisible: false,
        formLabelWidth: '120px',
        rules: {
          allotSeleted: [
            {required: true, message: '请选择要分配的公司', trigger: 'blur'},
          ],
          batchCount:[
            {validator: CheckBatchNum, trigger: 'blur'},
          ],
          newFolder:[
            {required: true, message: '请填写批次名称', trigger: 'blur'},
          ]
        },
        listQuery: {
          current: 1,
          pagesize: 10,
        },
        list: [],
        total: null,
        listLoading: false,
      }
    },
    created() {
      this.getOptions(); //加载基础选项值
      this.getAllotList();
    },
    computed:{
      ...mapGetters([
        'userInfo'
      ]),
      folderName(){
        return this.$route.query.id;
      }
    },
    beforeRouteEnter(to,from,next){
      next(vm => {
        vm.getAllotList();
      })
    },
    methods: {
      selectChange(val){
        if(val !== 1){
          delete this.temp.vital
        }
      },
      getOptions() {
        getCompany().then(res => {
          this.companyArr = res.data.info;
        }).catch(res => {
          this.$message.error(res)
        })
        getAreaList().then(res => {
          let temp = res.data.area;
          this.areaList = temp;
        }).catch(res => {
          this.$message.error(res)
        })
        getFileList().then(res => {
          let temp = res.data.info;
          this.fileList = temp;
        }).catch(res => {
          this.$message.error(res)
        })
      },
      sys_remoteMethod(query) {
        if (query !== "") {
          this.sysLoading = true;
          getSyslabel(query)
            .then(res => {
              this.sysLoading = false;
              let temp = res.data.sysLabel;
              this.systemlabel = temp;
            })
            .catch(res => {
              this.sysLoading = false;
              this.$message.error(res);
            });
        }
      },
      key_remoteMethod(query) {
        if (query !== "") {
          this.keyLoading = true;
          getKeyword(query)
            .then(res => {
              this.keyLoading = false;
              let temp = res.data.keyword;
              this.keyword = temp;
            })
            .catch(res => {
              this.keyLoading = false;
              this.$message.error(res);
            });
        }
      },
      getAllotList(){
        this.listLoading = true;
        let temp = Object.assign({},this.temp,this.listQuery,{'status':1},{'folder':this.folderName});
        temp = this.transData(temp);
        getAllotList(temp).then(res=>{
          this.list = res.data.info;
          this.total = res.data.total * 1;
          this.listLoading = false;
          //成功后 把查询条件 赋值给  searchTemp
          this.searchTemp = Object.assign({},this.temp);
          //把当前总条数给  totalTemp
          this.totalTemp = res.data.total * 1;
        }).catch(res=>{
          this.$message.error(res);
          this.listLoading = false;
        })
      },
      handleSizeChange(val) {
        this.listQuery.pagesize = val;
        this.getAllotList();
      },
      handleCurrentChange(val){
        this.listQuery.current = val;
        this.getAllotList();
      },
      sendEvent(){
        this.$refs.sendForm.validate(valid=>{
          if(!valid){
            return
          }
          if (!this.multipleSelection.length && !this.eventStatus != 1) { //如果未选中一条
            this.infoFormVisible = false;
            this.$message.error('您未有选中的操作项')
            return
          }
          let tempData = {customerId: this.multipleSelection,folder:this.folderName};
          setAllot(tempData).then(res => {
            //完成后 再次请求列表
            this.getAllotList();
            this.$message.success('选中移除成功');
            this.infoFormVisible = false;
          }).catch(res => {
            this.$message.error(res)
            this.infoFormVisible = false;
          })
        })
      },
      batchSendEvent(){ //批量操作
        this.$refs.sendForm.validate(valid=>{
          if(!valid){
            return
          }
          let fullLoading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          //是否点击的批量
          let stus = 1 ;  // 1 : 批量删除  2 : 批量分配;
          let tempData = {
            count: this.allot.batchCount ,
            status : stus ,
            folder : this.folderName
          };
          // 先获取 activeName 对应的 搜索结果集
          tempData = this.transData(Object.assign({},this.searchTemp,tempData))
          batchAllot(tempData).then(res => {
            fullLoading.close(); //关闭遮罩
            //完成后 再次请求列表
            this.getAllotList();
            this.$message.success('批量移除成功');
            this.infoFormVisible = false;
          }).catch(res => {
            fullLoading.close(); //关闭遮罩
            this.$message.error(res)
            this.infoFormVisible = false;
          })
        })
      },
      transfert(){ //数据转发
        this.$refs.sendForm.validate(valid=>{
          if(!valid){
            return
          }
          let fullLoading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          //是否点击的批量
          let tempData = {
            count: this.allot.batchCount ,
            companyId :this.allot.allotSeleted,
            folder : this.folderName,
            newFolder : this.allot.newFolder,
            applicantId:this.userInfo.userId
          };
          tempData = Object.assign({},tempData,this.searchTemp)
          transfert(tempData).then(res => {
            fullLoading.close(); //关闭遮罩
            this.getAllotList();
            this.$message.success(res.msg);
            this.infoFormVisible = false;
          }).catch(res => {
            fullLoading.close(); //关闭遮罩
            this.$message.error(res)
            this.infoFormVisible = false;
          })
        })
      },
      cancledialog(userForm) {
        //重置表单
        this.$refs[userForm].resetFields();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val.map(v => v.customerId);
      },
      transData(tempObj, status) {
        for (var k in tempObj) {
          if (k === 'areaOptions') {
            //提取地区的值
            if (tempObj[k].length) {
              tempObj['provinceId'] = tempObj[k][0];
              if (tempObj[k].length > 1) {
                tempObj['cityId'] = tempObj[k][1];
              }
              delete tempObj[k]
            } else {
              delete tempObj[k]
            }
          } else {
            //删除空值
            tempObj[k] === '' ? delete tempObj[k] : null;
          }
        }
        return tempObj
      },
      batchEvent(val){
        this.infoFormVisible = true;
        this.eventStatus = val;
      },
      getMarkText(eventStatus){
        if(eventStatus == 1){
          return '使用于少量目标数据移除。将列表中勾选的数据移除。'
        }else if(eventStatus == 2){
          return '适用于大批量数据移除,输入想要移除的数据数量，选择目标公司。(一次最多移除'+ this.maxBatchNum +'条)'
        }else {
          return '适用于公司间数据批量转移，输入想要转移的数据数量，选择目标公司。(一次最多移除'+ this.maxBatchNum +'条) '
        }
      },
      getEventMethod(status){
        if(status == 1){
          this.sendEvent();
        }else if(status == 2){
          this.batchSendEvent();
        }else{
          this.transfert();
        }
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .stock {
    .eventBtn {
      margin-left: 15px;
    }
    .dialog-Item {
      margin-bottom: 15px;
      margin-left: 15px;
      .textItem {
        display: inline-block;
        width: 40%;
      }
    }
    .info-item {
      margin: 15px 0px 15px 50px;
      > div {
        display: inline-block;
        min-width: 250px;
      }
      .tipText {
        display: inline-block;
        margin-right: 10px;
        min-width: 100px;
        text-align: right;
      }
    }
    .batchMark {
      text-indent:35px;
      font-size: 12px;
      color:#888;
      margin: 0 15px;
    }
  }
</style>
